package com.jfinal_demo.app.controllers;

import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal_demo.app.authenticate.Authenticate;
import com.jfinal_demo.app.authenticate.LoginInfo;
import com.jfinal_demo.app.model.User;
import com.jfinal_demo.app.services.UserService;
import com.jfinal_demo.app.validators.UserInfoValidator;

public class UserController extends BaseController {
    private final UserService userService = enhance(UserService.class);

    @Authenticate(false)
    @Before({POST.class, UserInfoValidator.class})
    public void register() {
        String userName = getPara("userName");
        String password = getPara("password");

        userService.register(userName, password);
        succeed();
    }

    @Authenticate(false)
    @Before({POST.class, UserInfoValidator.class})
    public void login() {
        String userName = getPara("userName");
        String password = getPara("password");

        User user = userService.getUser(userName, password);
        if (user == null) throw new RuntimeException("login failed");

        setSessionAttr(LoginInfo.SESSION_KEY, new LoginInfo(user.getId()));
        succeed();
    }
}
